package com.young4j.xinsuiwutuobang.framework;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.young4j.xinsuiwutuobang.bean.Data;
import com.young4j.xinsuiwutuobang.bean.Handler;
import com.young4j.xinsuiwutuobang.bean.Param;
import com.young4j.xinsuiwutuobang.bean.View;
import com.young4j.xinsuiwutuobang.util.ArrayUtils;
import com.young4j.xinsuiwutuobang.util.BeanHelper;
import com.young4j.xinsuiwutuobang.util.CodecUtils;
import com.young4j.xinsuiwutuobang.util.ConfigUtils;
import com.young4j.xinsuiwutuobang.util.ControllerHellper;
import com.young4j.xinsuiwutuobang.util.HelperLoader;
import com.young4j.xinsuiwutuobang.util.JsonUtils;
import com.young4j.xinsuiwutuobang.util.ReflectionUtils;
import com.young4j.xinsuiwutuobang.util.StreamUtls;
/**
 * 请求转发器
 * @author 杨飞
 *
 */
@WebServlet(urlPatterns = "/*",loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {
	@Override
	public void init(ServletConfig config) throws ServletException {
		/**
		 * 初始化Helper类
		 */
		HelperLoader.init();
		/**
		 * 获取ServletContxt对象（用于注册Servlet）
		 */
		ServletContext servletContext = config.getServletContext();
		/**
		 * 注册处理JSP的Servlet
		 */
		ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
		jspServlet.addMapping(ConfigUtils.getAppJspPath() + "*");
		/**
		 * 注册处理静态资源的默认Servlet
		 */
		ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
		defaultServlet.addMapping(ConfigUtils.getAppAssetPath() + "*");
	}
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		/**
		 * 获取请求方法和请求路径
		 */
		String requestMethod = req.getMethod().toLowerCase();
		String requestPath = req.getPathInfo();
		/**
		 * 获取Action处理器
		 */
		Handler handler = ControllerHellper.getHandler(requestMethod, requestPath);
		if(handler != null){
			/**
			 * 获取Controller类及bean实例
			 */
			Class<?> controllerClass = handler.getControllerClass();
			Object controllerObjectBean = BeanHelper.getBean(controllerClass);
			/**
			 * 创建请求参数对象
			 */
			Map<String,Object> paramMap = new HashMap<String, Object>();
			/**
			 * req参数与Enumeration实例的应用
			 */
			Enumeration<String> paramNames = req.getParameterNames();
			while(paramNames.hasMoreElements()){
				String paramName = paramNames.nextElement();
				String paramValue = req.getParameter(paramName);
				paramMap.put(paramName, paramValue);
			}
			String body = CodecUtils.decodeURL(StreamUtls.getString(req.getInputStream()));
			if(StringUtils.isNotBlank(body)){
				String[] params = StringUtils.split(body,"&");
				if(ArrayUtils.isNotEmpty(params)){
					for(String param : params){
						String [] array = StringUtils.split(param, "=");
						if(ArrayUtils.isNotEmpty(array) && array.length == 2){
							String paramName = array[0];
							String paramValue = array[1];
							paramMap.put(paramName, paramValue);
						}
					}
				}
			}
			Param param = new Param(paramMap);
			/**
			 * 调用Action方法
			 */
			Method actionMethod = handler.getActionMethod();
			Object result = ReflectionUtils.invokeMethod(controllerObjectBean, actionMethod, param);
			/**
			 * 处理Action方法返回值
			 */
			if(result instanceof View){
				/**
				 * 返回页面
				 */
				View view = (View) result;
				String path = view.getPath();
				if(StringUtils.isNotBlank(path)){
					if(path.startsWith("/")){
						resp.sendRedirect(req.getContextPath() + path);
					}else{
						Map<String,Object> model = view.getModel();
						for(Map.Entry<String, Object> entry:model.entrySet()){
							req.setAttribute(entry.getKey(), entry.getValue());
						}
						req.getRequestDispatcher(ConfigUtils.getAppJspPath() + path).forward(req, resp);
					}
				}else if(result instanceof Data){
					/**
					 * 返回JSON数据
					 */
					Data data = (Data) result;
					Object model = data.getModel();
					if(model != null){
						resp.setContentType("application/json");
						resp.setCharacterEncoding("UTF-8");
						PrintWriter writer = resp.getWriter();
						String json = JsonUtils.toJson(model);
						writer.write(json);
						writer.flush();
						writer.close();
					}
				}
			}
		}
	}
}
